<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="63px">
        <el-form-item label="状态">
          <el-select
            v-model="searchParam.exceptionHandleStatus"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ErrorHandleStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '使用部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('使用部门')"
            :selectData="searchParam.usingDepartmentId"
          />
        </el-form-item>
        <el-form-item label="位置">
          <el-tree-select
            placeholder="请输入位置"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="设备信息">
          <el-input
            v-model="searchParam.assetInfo"
            placeholder="请输入设备编码或名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="来源">
          <el-select
            v-model="searchParam.taskKind"
            placeholder="请选择来源"
            @keyup.enter="search"
            clearable
          >
            <!-- <el-option
              v-for="item in useDictionary('EamFaultSource')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> -->
            <el-option label="巡检" value="1" />
            <el-option label="点检" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="发现时间">
          <el-date-picker
            v-model="searchParam.arrivalDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="selections.length === 0"
          @click="batchRepair"
          ><i-ep-setting />批量故障报修</el-button
        >
        <!-- <el-button
          type="danger"
          :disabled="selections.length === 0"
          @click="batchClose"
          ><i-ep-circleClose />批量异常关闭</el-button
        > -->
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        row-key="checkDetailId"
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
          :selectable="(row) => row.exceptionHandleStatus == 1"
        />
        <el-table-column
          sortable
          label="状态"
          min-width="110"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="
                scope.row.exceptionHandleStatus == 1
                  ? 'warning'
                  : scope.row.exceptionHandleStatus == 2
                  ? ''
                  : 'success'
              "
            >
              {{
                useDictionary(
                  "ErrorHandleStatus",
                  scope.row.exceptionHandleStatus
                )
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          label="设备编码"
          prop="assetCode"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          sortable
          label="设备名称"
          prop="assetName"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />

        <el-table-column
          sortable
          label="异常项"
          prop=""
          min-width="200"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            <span v-if="scope.row.standardValue === '1'">
              {{ scope.row.sopItemName ?? "" }}，标准值是：{{
                scope.row.sopItemStandard ?? ""
              }}，实际值是：{{ scope.row.sopItemValue ?? "" }}，不合格
            </span>
            <span v-if="scope.row.standardValue === '2'">
              {{ scope.row.sopItemName ?? "" }}，实际值是：{{
                scope.row.sopItemValue ?? ""
              }}，不合格
            </span>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          label="使用部门"
          prop="usingDepartmentName"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          sortable
          label="位置"
          prop="locationName"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />

        <el-table-column
          sortable
          label="来源"
          prop="taskKind"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              scope.row.taskKind == "1"
                ? "巡检"
                : scope.row.taskKind == "2"
                ? "点检"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          sortable
          label="发现人"
          prop="executePersonName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="发现时间"
          prop="arrivalDate"
          min-width="165"
          sortable
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ scope.row.workTime ?? "" }}
          </template>
        </el-table-column>

        <el-table-column
          sortable
          label="处理内容"
          prop="handleContent"
          min-width="150"
          show-overflow-tooltip
          align="left"
        />

        <el-table-column
          sortable
          label="维修部门"
          prop="repairDepartmentName"
          min-width="110"
          show-overflow-tooltip
          align="left"
        />

        <el-table-column
          label="处理时间"
          prop="handleTime"
          min-width="165"
          sortable
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          sortable
          label="处理人"
          prop="handleUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column fixed="right" label="操作" width="190" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              v-if="scope.row.exceptionHandleStatus == 1"
              @click="openDialog(scope.row)"
            >
              <i-ep-setting />
              故障报修
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              v-if="scope.row.repairOrderId"
              @click="openDialog(scope.row)"
            >
              <i-ep-setting />
              查看记录
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              :disabled="true"
              v-if="
                scope.row.exceptionHandleStatus == 3 && !scope.row.repairOrderId
              "
            >
              <i-ep-setting />
              故障报修
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.exceptionHandleStatus != 1"
              @click="closeItem(scope.row)"
            >
              <i-ep-circleClose />
              异常关闭
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <eam-repair-order-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :assetKind="assetKind"
      @reset-table="(id:string) => (id?.length ? getTableList() : search())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
import dayjs from "dayjs";
defineOptions({
  name: "EAMEQUERRORHANDLE",
  inheritAttrs: false,
});

const assetKind = 1;

// 请求参数
const requestApi = "/eam/anomaly/tracking/queryByPage";

// 是否需要分页
const pagination = true;
const initParam = reactive({
  assetKind: 1,
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetInfo: "",
  assetTypeId: "",
  locationId: "",
  usingDepartmentId: "",
  assetStatus: "",
  exceptionHandleStatus: "",
  manageDepartmentId: "",
  assetManagerId: "",
  repairManagerId: "",
  checkPerson: "",
  arrivalDateSearch: [],
  workTimeStart: "",
  workTimeEnd: "",
  assetKind: 1,
  taskKind: "",
};

const deleteParam = {
  api: "/eam/equAssetInfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  selections,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

onMounted(() => {
  getTableList();
});

// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamrepairorder/get/${id}`,
    method: "get",
    data: {
      assetKind,
    },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 新建报修 */
function openDialog(roleObj: any) {
  if (!roleObj.repairOrderId) {
    addDialog.title = "新增维修单";
    addDialog.data = {
      // checkDetailIds: [roleObj.checkDetailId],
      pointCheckDetailId: roleObj.checkDetailId,
      assetId: roleObj.assetId,
      remarks: filterRemarks([roleObj]),
      workTime: roleObj.workTime,
    };
    addDialog.readvisible = false;
  } else {
    addDialog.title = "查看维修单";
    roleObj.repairOrderId && getInfo(roleObj.repairOrderId);
    addDialog.readvisible = true;
  }
  addDialog.visible = true;
}

function batchRepair() {
  const isSameAssetId = areAllSameByProperty(selections.value, "assetId");
  let checkDetailIds: string[] = [];
  selections.value.map((e: any) => {
    checkDetailIds.push(e.checkDetailId);
  });
  if (isSameAssetId) {
    const roleObj = selections.value[0];
    addDialog.title = "新增维修单";
    addDialog.data = {
      pointCheckDetailId: checkDetailIds.join(","),
      assetId: roleObj.assetId,
      remarks: filterRemarks(selections.value),
      workTime: roleObj.workTime,
    };
    addDialog.visible = true;
    addDialog.readvisible = false;
  } else {
    ElMessage.error("请选择同一设备");
  }
}

function batchClose() {
  let checkDetailIds: string[] = [];
  selections.value.map((e: any) => {
    checkDetailIds.push(e.checkDetailId);
  });
  ElMessageBox.prompt("请填写异常关闭原因", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^\S+$/,
    inputErrorMessage: "异常关闭原因不能为空",
    modalClass: "closeItem",
  })
    .then(async ({ value }) => {
      ElMessage.info("开发中");
      // await request({
      //   url: `/eam/anomaly/tracking/close`,
      //   method: "post",
      //   data: {
      //     checkDetailId: checkDetailIds.join(","),
      //     remarks: value,
      //   },
      // }).then((res) => {
      //   ElMessage.success("异常关闭成功！");
      //   search();
      // });
    })
    .catch(() => {});
}

function areAllSameByProperty(arr: any, property: string) {
  if (arr.length === 0) return true; // 如果数组为空，则认为所有属性“相同”
  const firstValue = arr[0][property];
  return arr.every((item: any) => item[property] === firstValue);
}

// 过滤不合格原因
function filterRemarks(arr: any) {
  let txt = "";
  arr?.map((self: any, index: number) => {
    if (index !== 0) {
      txt += "\n";
    }
    if (self.standardValue === "1") {
      txt += `${self.sopItemName}，标准值是：${
        self.sopItemStandard ?? ""
      }，实际值是：${self.sopItemValue ?? ""}，不合格`;
    } else if (self.standardValue === "2") {
      txt += `${self.sopItemName}，实际值是：${
        self.sopItemValue ?? ""
      }，不合格`;
    }
  });
  return txt;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

const closeItem = (row: any) => {
  ElMessageBox.prompt("请填写异常关闭原因", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^\S+$/,
    inputErrorMessage: "异常关闭原因不能为空",
    modalClass: "closeItem",
  })
    .then(async ({ value }) => {
      await request({
        url: `/eam/anomaly/tracking/close`,
        method: "post",
        data: {
          checkDetailId: row.checkDetailId,
          remarks: value,
        },
      }).then((res) => {
        ElMessage.success("异常关闭成功！");
        search();
      });
    })
    .catch(() => {});
};

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = ids;
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = ids;
      personList.value = [];
      changeDept(ids, item);
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = ids;
      personList1.value = [];
      changeDept(ids, item);
    }
  } else {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = "";
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = "";
      searchParam.value.assetManagerId = "";
      personList.value = [];
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = "";
      searchParam.value.repairManagerId = "";
      personList1.value = [];
    }
  }
}

// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    if (name == "管理部门") {
      personList.value = res.data;
    }
    if (name == "维修部门") {
      personList1.value = res.data;
    }
  }
};
const dataObject = (item: string) => {
  return {
    name:
      item == "使用部门"
        ? "使用部门"
        : item == "管理部门"
        ? "管理部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 处理时间
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.workTimeStart = data[0];
    searchParam.value.workTimeEnd = data[1];
  } else {
    searchParam.value.workTimeStart = "";
    searchParam.value.workTimeEnd = "";
  }
}
onMounted(() => {
  getLocationInfoTree();
});
</script>

<style lang="scss" scoped>
:deep(.closeItem .el-message-box__input) {
  padding-top: 7px;
}
</style>
